import { Component, OnInit, OnDestroy, AfterViewInit, Input } from '@angular/core';
import { EquipmentService } from '../../equipment.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { NotificationService, BullySubjectService } from 'app/shared/service';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, filter } from 'rxjs/operators';
import { MESSAGE_CHANNEL, SYSTEM_EVENT } from 'app/app.constants';
import * as moment from 'moment';
import { differenceInCalendarDays } from 'date-fns';
import { TranslateService } from '@ngx-translate/core';
import { SystemService } from 'app/service/system.service';
import { AuthService } from 'app/auth/auth.service';

@Component({
    selector: 'itmp-equipment-alarm-list',
    templateUrl: './equipment-alarm-list.component.html',
    styleUrls: ['./equipment-alarm-list.component.css']
})
export class EquipmentAlarmListComponent implements OnInit, OnDestroy, AfterViewInit {
    @Input() accessButton;
    search$ = new Subject<object>();
    toolbarList = [
        // 工具条栏
        { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' },
        // { className: 'icon-screenfull' },
        { className: 'icon-xiazai' }
    ];
    renderHeader = [
        {
            name: 'Alarm_ID',
            key: null,
            value: 'alarmID',
            isChecked: true
        },
        {
            name: 'Equipment_ID',
            key: null,
            value: 'deviceID',
            isChecked: true
        },
        {
            name: 'Alarm_Source',
            key: null,
            value: 'alarmSource',
            isChecked: true
        },
        {
            name: 'Detection_Date',
            key: null,
            value: 'detectionTime',
            isChecked: true
        },
        {
            name: 'Ack_Date',
            key: null,
            value: 'ackTime',
            isChecked: true
        },
        {
            name: 'Description',
            key: null,
            value: 'description',
            isChecked: true
        },
        {
            name: 'Zone_ID',
            key: null,
            value: 'zoneID',
            isChecked: true
        } /*,
        {
            name: 'Status',
            key: null,
            value: 'Status',
            isChecked: true
        }*/
    ];
    searchData: any;
    pagination: any;
    selectAlarm: any;
    subscripions: Subscription[] = [];
    dateArr: any;
    // 筛选框下拉列表
    selectionList = {
        // Alarm_Source: ['DMS', 'AID', 'CCTV', 'LPR']
        Alarm_Source: ['VMS', 'VD', 'CCTV', 'TSC']
    };
    listOfData = [];
    zoneIdList = [];
    userZoneIdList = [];
    isForce = false;
    isForceClear = false;
    isForceVisible = false;
    isForceClearVisible = false;

    constructor(
        private eqt: EquipmentService,
        private msg: NotificationService,
        private message: NzMessageService,
        private modalService: NzModalService,
        private bully: BullySubjectService,
        private translate: TranslateService,
        private ss: SystemService,
        private authService: AuthService
    ) {}

    ngOnInit() {
        this.getZoneIdListByUser();
        this.searchPipeSet();
        // 订阅stomp ws 事件
        /*const subscripion = this.bully.getSubject().subscribe(res => {
            // alarm
            if (res['type'] === SYSTEM_EVENT.ALARM_EVENT) {
                const features = {
                    ...res.data,
                    ackTime: res.data.ackTime && res.data.ackTime.time,
                    // alarmCode: res.data.alarmCode,
                    // alarmId: res.data.alarmId,
                    // alarmSource: res.data.alarmSource,
                    // clearTime: res.data.clearTime && res.data.clearTime.time,
                    // description: res.data.description,
                    detectionTime: res.data.detectionTime && res.data.detectionTime.time,
                    // deviceID: res.data.deviceID,
                    // deviceType: res.data.deviceType,
                    // latitude: res.data.latitude,
                    // longitude: res.data.longitude,
                    // opeStatus: res.data.opeStatus,
                    // zoneID: res.data.zoneID,
                    active: true
                };
                this.getAlarmBySocket(features);
            }
        });
        this.subscripions.push(subscripion);*/
        this.initData();
        // this.getData();
        // 监听header select zone操作
        this.bully.zoneListBehavior.subscribe(res => {
            this.zoneIdList = res['selectZoneList'] ? res['selectZoneList'] : [];
            this.getData();
        });
    }

    // 初始化分页和搜索数据
    initData() {
        this.pagination = {
            totalEle: 10,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
        this.searchData = {
            alarmID: null,
            deviceID: null,
            alarmSource: null,
            ackTime: {
                startTime: null,
                endTime: null
            },
            detectionTime: {
                startTime: null,
                endTime: null
            },
            alarmCode: null,
            description: null,
            zoneID: null
        };
        this.dateArr = {
            detectionTime: [],
            ackTime: []
        };
        this.listOfData = [];
    }

    ngAfterViewInit(): void {
        /*const subscripion = this.bully
            .getBSubject()
            .pipe(filter(res => !!res))
            .subscribe(res => {
                if (res['type'] === SYSTEM_EVENT.ALARM_EVENT) {
                    const features = {
                        ...res.data,
                        ackTime: res.data.ackTime && res.data.ackTime.time,
                        // alarmCode: res.data.alarmCode,
                        // alarmId: res.data.alarmId,
                        // alarmSource: res.data.alarmSource,
                        // clearTime: res.data.clearTime && res.data.clearTime.time,
                        // description: res.data.description,
                        detectionTime: res.data.detectionTime && res.data.detectionTime.time,
                        // deviceID: res.data.deviceID,
                        // deviceType: res.data.deviceType,
                        // latitude: res.data.latitude,
                        // longitude: res.data.longitude,
                        // opeStatus: res.data.opeStatus,
                        // zoneID: res.data.zoneID,
                        active: true
                    };
                    setTimeout(() => this.getAlarmBySocket(features));
                }
            });
        this.subscripions.push(subscripion);*/
    }

    ngOnDestroy() {
        this.bully.resetBSubject();
        this.subscripions.forEach((subscripion, index) => {
            subscripion.unsubscribe();
        });
    }

    // 防抖函数注册
    searchPipeSet() {
        const subscripion = this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.pagination.currentPage = 1;
            this.getData();
        });
        this.subscripions.push(subscripion);
    }

    // 搜索(防抖)
    onSearch(name): void {
        this.search$.next({ name: this.searchData[name] });
    }

    // websocket获取数据
    getAlarmBySocket(data) {
        this.listOfData.pop();
        this.listOfData.forEach((item, index) => {
            if (item.active) {
                this.listOfData[index].active = false;
                return;
            }
        });
        this.listOfData = [data, ...this.listOfData];
        this.listOfData[0].clearTime = this.eqt.changeDate(this.listOfData[0].clearTime, 1);
        this.listOfData[0].detectionTime = this.eqt.changeDate(this.listOfData[0].detectionTime, 1);
        this.listOfData[0].ackTime = this.eqt.changeDate(this.listOfData[0].ackTime, 1);
        this.selectAlarm = this.listOfData[0];
    }

    getData() {
        const params = {
            condition: { ...this.searchData, zoneIdList: this.zoneIdList },
            exportType: null,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.eqt.getAlarmList(params).subscribe(res => {
            const data = res.data;
            if (!data) {
                this.listOfData = [];
                return;
            }
            this.listOfData = data.list;
            this.pagination.currentSize = data.numberOfElements;
            this.pagination.totalEle = data.totalCount;
            this.listOfData.forEach((item, index) => {
                this.listOfData[index].clearTime = this.eqt.changeDate(item.clearTime, 1);
                this.listOfData[index].detectionTime = this.eqt.changeDate(item.detectionTime, 1);
                this.listOfData[index].ackTime = this.eqt.changeDate(item.ackTime, 1);
            });
        });
    }

    // 刷新
    refresh(): void {
        this.searchData = null;
        this.initData();
        this.getData();
    }

    // 点击tr取值
    clickTR(i): void {
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                this.selectAlarm = data;
            }
        });
    }

    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        const total = this.pagination.totalEle;
        const curPage = this.pagination.currentPage;
        this.pagination.currentPage = Math.ceil(total / e) < curPage ? Math.ceil(total / e) : curPage;
        this.getData();
    }

    // 获取用户的ZoneIdList
    getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.eqt.getAllUser(queryData).subscribe(res => {
            const userZone = res.content.content[0].userZoneRel;
            userZone.forEach(zoneId => {
                this.userZoneIdList.push(zoneId.vnqn_zone_id);
            });
            this.getData();
        });
    }

    // 取消强制操作
    FourchHandleCancel() {
        this.isForceVisible = false;
        this.isForceClearVisible = false;
    }

    // 确定强制操作
    ForceHandleOk() {
        this.isForceVisible = false;
        this.isForce = true;
        const header = {
            zoneId: this.userZoneIdList.join(','),
            isForce: true
        };
        this.eqt.putAckAlarm(this.selectAlarm, header).subscribe(res => {
            this.getData();
            this.selectAlarm = null;
        });
    }

    ForceClearHandleOk() {
        this.isForceClearVisible = false;
        this.isForceClear = true;
        const header = {
            zoneId: this.userZoneIdList.join(','),
            isForce: true
        };
        this.eqt.putFalseAlarm(this.selectAlarm, header).subscribe(res => {
            this.getData();
            this.selectAlarm = null;
        });
    }

    // ask
    askAlarm() {
        if (this.selectAlarm && this.selectAlarm.alarmId) {
            if (!this.authService.isUserZoneChecked(this.selectAlarm.zoneID)) {
                return;
            }
            const zoneIds = this.ss.userZoneList.filter(z => !z.isTemp).map(z => z.id);
            const header = {
                zoneId: zoneIds.join(','),
                isForce: this.isForce
            };
            const tempTranslate = [
                { title: 'EquipmentManagement.equipmentAlarm.Ack_Alarm' },
                { title: 'EquipmentManagement.equipmentAlarm.Are you to Ack this Alarm' },
                { title: 'EquipmentManagement.equipmentAlarm.YES' },
                { title: 'EquipmentManagement.equipmentAlarm.No' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont " style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.eqt.putAckAlarm(this.selectAlarm, header).subscribe(res => {
                        // this.getData();
                        // this.selectAlarm = null;
                        if (res['msg'] && res['msg'].indexOf('No operation permissions') > -1) {
                            this.isForceVisible = true;
                        } else {
                            this.getData();
                            this.selectAlarm = null;
                        }
                    });
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        } else {
            this.msg.notify({ type: 'warning', path: 'EquipmentManagement.equipmentAlarm.select_notify' });
            // 提示用户没有选中项目
        }
    }

    // false
    falseAlarm(type) {
        const confirm = () => {
            if (!this.authService.isUserZoneChecked(+this.selectAlarm.zoneID)) {
                return;
            }
            const zoneIds = this.ss.userZoneList.filter(z => !z.isTemp).map(z => z.id);
            const header = {
                zoneId: zoneIds.join(','),
                isForce: this.isForceClear
            };

            const tempTranslate = [
                { title: 'EquipmentManagement.equipmentAlarm.False_Alarm' },
                { title: 'EquipmentManagement.equipmentAlarm.Are you sure to False this Alarm' },
                { title: 'EquipmentManagement.equipmentAlarm.YES' },
                { title: 'EquipmentManagement.equipmentAlarm.No' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont " style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    /*const params = [
                        {
                            alarmCode: this.selectAlarm.alarmCode,
                            eqtId: this.selectAlarm.deviceID
                        }
                    ];*/
                    this.eqt.putFalseAlarm(this.selectAlarm, header).subscribe(res => {
                        if (res['msg'] && res['msg'].indexOf('No operation permissions') > -1) {
                            this.isForceClearVisible = true;
                        } else {
                            this.getData();
                            this.selectAlarm = null;
                        }
                    });
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        };
        if (this.selectAlarm && this.selectAlarm.alarmId) {
            if (type === 'False') {
                if (this.selectAlarm.ackTime) {
                    this.msg.notify({ type: 'warning', path: 'EquipmentManagement.equipmentAlarm.false_notify' });
                    return;
                } else {
                    confirm();
                }
            } else {
                if (!this.selectAlarm.ackTime) {
                    this.msg.notify({ type: 'warning', path: 'EquipmentManagement.equipmentAlarm.clear_notify' });
                    return;
                } else {
                    confirm();
                }
            }
        } else {
            this.msg.notify({ type: 'warning', path: 'EquipmentManagement.equipmentAlarm.select_notify' });
            // 提示用户没有选中项目
        }
    }

    // 日历框事件
    onDateOk(result: Date, type): void {
        /*
        if (this.dateArr.detectionTime) {
            const a = new Date(moment(this.dateArr.detectionTime[0]).format('YYYY-MM-DD 00:00:00')).getTime();
            const b = new Date(moment(this.dateArr.detectionTime[1]).format('YYYY-MM-DD 23:59:59')).getTime();
            this.searchData.detectionTime = {
                startTime: this.eqt.changeDate(this.dateArr.detectionTime && a, 0),
                endTime: this.eqt.changeDate(this.dateArr.detectionTime && b, 0)
            };
            this.onSearch('detectionTime');
        }
        if (this.dateArr.ackTime) {
            const c = new Date(moment(this.dateArr.ackTime[0]).format('YYYY-MM-DD 00:00:00')).getTime();
            const d = new Date(moment(this.dateArr.ackTime[1]).format('YYYY-MM-DD 23:59:59')).getTime();
            this.searchData.ackTime = {
                startTime: this.eqt.changeDate(this.dateArr.ackTime && c, 0),
                endTime: this.eqt.changeDate(this.dateArr.ackTime && d, 0)
            };
            this.onSearch('ackTime');
        }*/
        this.searchData[type] = {
            startTime: result[0]
                ? moment(result[0])
                      .startOf('day')
                      .valueOf()
                : null,
            endTime: result[1]
                ? moment(result[1])
                      .endOf('day')
                      .valueOf()
                : null
        };
        this.onSearch(type);
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
